<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace buwang\middleware;

use app\manage\model\Token;
use buwang\interfaces\MiddlewareInterface;
use buwang\traits\JwtTrait;
use app\Request;
use think\facade\View;

class ViewInit implements MiddlewareInterface
{
    use JwtTrait;

    public function handle(Request $request, \Closure $next)
    {
        $token = get_token($request);
        $user_id = 0;
        if ($token) {//登录过
            try{
                $jwtinfo = self::decodeToken($token);//解析token,获取用户信息
                $user = Token::validateRedisToken($token, $jwtinfo);
                $user && $user_id = $user->id;
            }catch (\Throwable $e){
                $user_id = 0;
            }
        }
        list($thisModule, $thisController, $thisAction) = [app('http')->getName(), $request->controller(), $request->action()];
        list($thisControllerArr, $jsPath) = [explode('.', $thisController), null];
        foreach ($thisControllerArr as $vo) {
            empty($jsPath) ? $jsPath = parse_name($vo) : $jsPath .= '/' . parse_name($vo);
        }
        $autoloadJs = file_exists(root_path('public') . "static/{$thisModule}/js/{$jsPath}.js") ? true : false;
        $thisControllerJsPath = "{$thisModule}/js/{$jsPath}.js";
        $adminModuleName = $thisModule;
        $isSuperAdmin = $user_id == config('auth.super_admin_id');
        $data = [
            'adminModuleName' => $adminModuleName,
            'thisController' => parse_name($thisController),
            'thisAction' => $thisAction,
            'thisRequest' => parse_name("{$thisModule}/{$thisController}/{$thisAction}"),
            'thisControllerJsPath' => "{$thisControllerJsPath}",
            'autoloadJs' => $autoloadJs,
            'isSuperAdmin' => $isSuperAdmin,
            'domain'=>$request->domain(),
            'version' => env('app_debug') ? time() : BW_VERSION,
        ];
        View::assign($data);
        return $next($request);
    }


}